package com.example.Gethome.controller;

import com.example.Gethome.entity.Home;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;

@Controller
@Slf4j
public class ImageTest {

    private static String UPLOAD_PATH = "File/image/upload";

    // 上传图片
    // 同时根据房屋名称来添加路径
    @RequestMapping(path = "uploadImage", method = RequestMethod.POST)
    @ResponseBody
    // @RequestParam("file")
    public String uploadImage (@RequestParam("file") MultipartFile file) {
        try {
            String name = file.getOriginalFilename();
            System.out.println(name);
            InputStream inputStream = file.getInputStream();
            Path directory = Paths.get(UPLOAD_PATH);
            if(!Files.exists(directory)) {
                Files.createDirectories(directory);
            }
            long copy = Files.copy(inputStream, directory.resolve(name));
            System.out.println("url访问路径为" + UPLOAD_PATH + "/" + name);
            return "http://39.106.79.148:7000/" + UPLOAD_PATH + "/" + name;
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            return "上传失败";
        }
    }
}
